/**
 * @file
 * @auth jinguangguo
 * @date 2016/10/19
 */

import filter from '../../grsc-base/util/filter';
import cookie from '../../grsc-base/util/cookie';
import parseUrl from '../../grsc-base/util/parseUrl';
import {
    REG_URL,
    CURRENCY_RMB
} from '../../grsc-base/common/constants';
import MathTool from '../../grsc-base/util/mathtool';
import commonLang from './commonLang';
import commonService from '../../grsc-base/common/commonService';

const PAY_TYPE_ALIPAY = 'ALIPAY';
const PAY_TYPE_BANK = 'BANK';

export default {
    filter: filter,

    /**
     * 过去当地时区
     */
    getCurrentTimezone() {
        let d = new Date();
        return d.getTimezoneOffset() / 60;
    },

    getAccountNo() {
        return window.localStorage.getItem('account-no');
    },

    /**
     * 做登录之后的处理
     */
    doLogin(token, userAccount, isToExchangePage = true) {
        cookie.set('LOGIN_TOKEN', token, {
            path: '/',
            expires: 1 // 默认一个小时
        });
        window.localStorage.setItem('account-no', userAccount);

        if (isToExchangePage === true) {
            goPage();
        }

        function goPage() {
            let query = parseUrl();
            let to = window.decodeURIComponent(query.from);
            if (REG_URL.test(to) === true) {
                window.location.href = to;
            } else {
                window.location.href = './index.html';
            }
        }

    },

    /**
     * 登出
     * config.to    要去跳转的页面
     */
    doLogout(config) {
        cookie.remove('LOGIN_TOKEN', {
            path: '/'
        });
        window.localStorage.removeItem('account-no');

        let href = './index.html';
        if (config && config.to) {
            href = config.to;
        }

        window.location.href = href;
    },

    setAuthLevel1(accountNo) {
        window.sessionStorage.setItem('HAS_AUTH_' + window.localStorage.getItem('account-no'), '1');
        return window.sessionStorage.setItem('HAS_AUTH_' + accountNo, '1')
    },

    setAuthLevel2(accountNo) {
        window.sessionStorage.setItem('HAS_AUTH_' + window.localStorage.getItem('account-no'), '2');
        return window.sessionStorage.setItem('HAS_AUTH_' + accountNo, '2')
    },

    removeAuth(accountNo) {
        window.sessionStorage.removeItem('HAS_AUTH_' + window.localStorage.getItem('account-no'));
        window.sessionStorage.removeItem('HAS_AUTH_' + accountNo);
    },

    /**
     * 是否登录
     * @returns {boolean}
     */
    isLogin() {
        return cookie.get('LOGIN_TOKEN') ? true : false;
    },

    /**
     * 用户是否已经实名
     */
    hasAuth() {
        return this.hasAuthLevel1() || this.hasAuthLevel2();
    },

    hasAuthLevel1() {
        let accountNo = this.getAccountNo();
        return window.sessionStorage.getItem('HAS_AUTH_' + accountNo) === "1" ? true : false;
    },

    /**
     * 是否已经进行KYC认证
     * @returns {boolean}
     */
    hasAuthLevel2() {
        let accountNo = this.getAccountNo();
        return window.sessionStorage.getItem('HAS_AUTH_' + accountNo) === "2" ? true : false;
    },

    /**
     * 复制
     * @param element
     */
    copy(element) {
        element.select();
        let $element = $(element);
        $element.addClass('fn-selected');
        document.execCommand("Copy");

        element.blur();

        setTimeout(() => {
            $element.removeClass('fn-selected');
        }, 2000); // 与ToastTip时间相同

        window.success(commonLang[window.app.LANG].success, () => {
            $element.removeClass('fn-selected');
        });
    },

    /**
     * 判断是否已经登录
     * @param next
     */
    checkLogin(next) {
        if (this.isLogin() === true) {
            next();
        } else {
            window.location.href = './login.html';
        }
    },

    /**
     * 判断是否实名
     * @param next
     */
    checkAuth(next) {
        if (this.hasAuth() === true) {
            next();
        } else {
            window.location.href = './account.html#/certification';
        }
    },

    /**
     * 判断登录和实名认证
     * @param next
     */
    checkLoginAndAuth(next) {
        if (this.isLogin() === true) {
            if (this.hasAuth() === true) {
                next();
            } else {
                window.location.href = './account.html#/certification';
            }
        } else {
            window.location.href = './login.html';
        }
    },

    /**
     * 获取手机字符串
     */
    getPhoneSuffix() {
        if (window.app.user.requested === false) {
            throw new Error('No login ...');
        }
        return window.app.user.value.mobileText;
    },
    /**
     * 获取手机字符串
     */
    getEmailSuffix() {
        if (window.app.user.requested === false) {
            throw new Error('No login ...');
        }
        return window.app.user.value.emailText;
    },

    /**
     * 获取ID类型列表
     */
    getIdTypeList(_country) {
        switch (_country) {
            case 'us':
                return [{
                    label: 'ID Card',
                    val: 'ID_CARD'
                }, {
                    label: 'Passport',
                    val: 'PASSPORT'
                },

                    // {
                    //     label: 'Diver License',
                    //     val: 'DIRVING_LICENSE'
                    // }
                ]
                break;
            case 'es':
                return [{
                    label: 'pasaporte',
                    val: 'PASSPORT'
                },
                {
                    label: 'Tarjeta de identidad',
                    val: 'ID_CARD'
                }
                ]
                break;
            case 'hk':
                return [{
                    label: '中國大陸地區身份證',
                    val: 'ID_CARD'
                },{
                    label: '護照',
                    val: 'PASSPORT'
                },
                
                ]
                break;

            case 'cn':
                return [{
                    label: '中国大陆地区身份证',
                    val: 'ID_CARD'
                },{
                    label: '护照',
                    val: 'PASSPORT'
                },
                
                ]
                break;
        }

    },

    /**
     * uid格式化显示
     * @param uid
     * @returns {*}
     */
    getFormattedUid(uid) {
        const BASE_UID_NO = 100000;
        return MathTool.add(BASE_UID_NO, uid);
    },

    /**
     * 是否是移动端
     * @returns {boolean}
     */
    isMobile() {
        let userAgentInfo = navigator.userAgent;
        let Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
        let flag = false;
        for (let v = 0; v < Agents.length; v++) {
            if (userAgentInfo.indexOf(Agents[v]) > 0) {
                flag = true;
                break;
            }
        }
        return flag;
    },

    /**
     * 判断是否是移动端   跳转到相应的页面
     * @param goToPage  string
     * @return boolean
     */
    isGoMobilePage(goToPage) {
        if (this.isMobile() && window.location.href.indexOf(goToPage) < 0) {
            // 移动端跳转
            window.location.href = goToPage;
        }
    },

    // CNZZ 埋点
    stat(dataArr, cbfn) {
        if (window._czc) {
            _czc.push(dataArr);

            if (cbfn) {
                setTimeout(() => {
                    cbfn && cbfn();
                }, 400)
            }
        } else {
            if (cbfn) {
                cbfn();
            }
        }
    },
    isNeedStat() {
        return window.app.isNeedStat
    },

    /**
     * symbol交易对转换
     * @param symbol
     * @returns {string}
     */
    revertCoin(symbol) {
        let ss = symbol.split('_');
        return ss[1] + '_' + ss[0];
    },

    /**
     * 根据symbol来获得展示
     * @param symbol
     */
    getSymbolLabel(symbol) {
        let ss = symbol.split('_');
        let coin = ss[1].toUpperCase();
        let unit = ss[0].toUpperCase();
        return coin + ' / ' + unit;
    },

    /**
     * 根據payInfoList來獲取支付方式列表
     * @param payInfoList
     */
    getBanksByPayInfo(payInfoList) {
        let results = [];
        $.map(payInfoList, (item, index) => {
            if (item === PAY_TYPE_ALIPAY) {
                results.push('支付寶');
            } else if (item === PAY_TYPE_BANK) {
                results.push('銀行卡');
            } else {
                results.push('不支持');
            }
        });
        return results.join('/');
    },

    // 这些价格均已美元标价
    currentBtcPrice: -1,
    currentEthPrice: -1,
    currentActPrice: -1,
    /**
     * 获取当前币价格
     * @param assetCode
     * @param callback
     */
    getCurrentPriceByCoin(assetCode, callback) {
        let that = this;
        if (this.currentBtcPrice < 0) {
            // commonService.getBitfinexBtcPrice().done(rep => {
            //     if (rep.code === window.CODE.SUCCESS) {
            //         this.currentBtcPrice = rep.data.last_price;
            //         console.log('[lib] this.currentBtcPrice:' + this.currentBtcPrice);
                   
            //     } else {
            //         window.error(rep.msg);
            //     }
            // });
            start(assetCode, callback);
        } else {
            start(assetCode, callback);
        }

        function start(assetCode, callback) {
            if (assetCode === 'BTC') {
                callback({
                    priceUSD: that.currentBtcPrice,
                    priceCNY: filter.floorFixPrice(MathTool.multiplication(that.currentBtcPrice, CURRENCY_RMB), 2)
                });
            } else if (assetCode === 'USC') {
                callback({
                    priceUSD: 1,
                    priceCNY: filter.floorFixPrice(MathTool.multiplication(1, CURRENCY_RMB), 2)
                });
            } else {
                let symbol = 'BTC_' + assetCode;

                commonService.getTradeDetail().done(rep => {
                    // this.currentEthPrice = rep['BTC_ETH'] && MathTool.multiplication(rep['BTC_ETH'].newPrice, this.currentBtcPrice);
                    that.currentActPrice = rep['BTC_ACT'] && MathTool.multiplication(rep['BTC_ACT'].newPrice, that.currentBtcPrice);
                    let repData = {
                        priceBTC: rep['BTC_ACT'].newPrice,
                        priceUSD: filter.floorFixPrice(that.currentActPrice, 2),
                        priceCNY: filter.floorFixPrice(MathTool.multiplication(that.currentActPrice, CURRENCY_RMB), 2)
                    };

                    callback(repData);
                });

            }
        }
    }

}